package com.banyuan.lesson.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/*
 * 两大优化
 * 1、可以有返回值；
 * 2、可以抛异常；*/
public class MyCallable implements Callable<Integer> {
    private int left;
    private int right;

    public MyCallable(int left, int right) {
        this.left = left;
        this.right = right;
    }

    public void setLeft(int left) {
        this.left = left;
    }

    public void setRight(int right) {
        this.right = right;
    }

    @Override
    public Integer call() throws Exception {
        for (int i = left; i <= right; i++) {
            System.out.println(Thread.currentThread() + "-" + i);
        }
        return 666;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Integer> callable1 = new MyCallable(1,100);
        Callable<Integer> callable2 = new MyCallable(100,200);
        FutureTask<Integer> futureTask1 = new FutureTask<>(callable1);
        FutureTask<Integer> futureTask2 = new FutureTask<>(callable2);
        Thread th1 = new Thread(futureTask1);
        Thread th2 = new Thread(futureTask2);
        th1.start();
        th2.start();
        //会等待两个子线程结束；
        int sum1 = futureTask1.get();
        int sum2 = futureTask1.get();
        System.out.println(sum1 + sum2);
    }
}
